<?php
// +----------------------------------------------------------------------
// | tpcms [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.tpcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: TPCMS < admin@tpcms.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
use \think\Session;
use app\admin\model\Admin as adminModel;//管理员模型
use app\admin\model\AdminMenu;
use app\admin\controller\Permissions;
use \think\Request;
use think\Validate;
class Admin extends Base
{
    public function _initialize() {
        $this->model = new adminModel();
        
    }
    /**
     * 管理员列表
     * @return [type] [description]
     */
    public function index()
    {
        //实例化管理员模型
        $model = new adminModel();
        $post = $this->request->param();
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['nickname'] = ['like', '%' . $post['keywords'] . '%'];
        }
        if (isset($post['central_cate_id']) and $post['central_cate_id'] > 0) {
            $where['central_cate_id'] = $post['central_cate_id'];
        }

        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
        }
		// var_dump(empty($where));die;
        $admin = empty($where) ? $model->where(['type'=>1])->order('create_time desc')->paginate(20) : $model->where(['type'=>1])->where($where)->order('create_time desc')->paginate(20,false,['query'=>$this->request->param()]);
        // var_dump($admin);die;
        $this->assign('admin',$admin);
        $info['cate'] = Db::name('admin_cate')->where(['type'=>1])->select();
        $this->assign('info',$info);
        return $this->fetch();
    }
    // 角色管理数据接口
    public function index_data(){
        if($this->request->isAjax()){
            $input = input(); 
            $page       = ($input['page']-1)*$input['limit'];
            $limit      = $input['limit'];
            $where=[];


            $data = db('admin_cate')->alias('a')
            ->join('admin c','a.id=c.admin_cate_id')
            ->field('c.id,c.login_ip,a.name admin_cate_name,c.nickname,c.name name,FROM_UNIXTIME(a.create_time,"%Y-%m-%d %H:%i:%s") as  create_time,FROM_UNIXTIME(c.login_time,"%Y-%m-%d %H:%i:%s") as login_time')
            ->limit($page,$limit)
            ->select();
            // var_dump($data);die;
            $count = db('admin_cate')->alias('a')
            ->join('admin c','a.id=c.admin_cate_id')
            ->count();
            

            return hSuccess('OK', $data,$count,ceil($count/$limit));
       }
    }
    /**
     * 管理员的添加及修改
     * @return [type] [description]
     */
    public function publish()
    {
    	//获取管理员id
    	$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new adminModel();
        
    	if($id > 0) {
    		//是修改操作
    		if($this->request->isPost()) {
    			//是提交操作
    			$post = $this->request->post();
    			//验证  唯一规则： 表名，字段名，排除主键值，主键名
	            
				$rule = [
				    'name'  => 'require|alphaDash',
				    'admin_cate_id'   => 'require',
				];
				
				$msg = [
				    'name.require' 		=> '管理员名称不能为空',
				    'name.alphaDash'	=> '用户名格式只能是字母、数字、——或_',
				    'admin_cate_id.require'  => '请选择管理员分组',
				];
				$validate   = Validate::make($rule,$msg);
	            //验证部分数据合法性
	            if (!$validate->check($post)) {
	                $this->error('提交失败：' . $validate->getError());
	            }
	            //验证用户名是否存在
	            $name = $model->where('id','<>',$post['id'])->where(['name'=>$post['name'],'type'=>1])->find();
	            if(!empty($name)) {
	            	return $this->error('提交失败：该用户名已被注册');
	            }
	            //验证昵称是否存在
	            $nickname = $model->where('id','<>',$post['id'])->where(['nickname'=>$post['nickname'],'type'=>1])->find();
				// var_dump($nickname);die;
	            if(!empty($nickname)) {
	            	return $this->error('提交失败：该昵称已被占用');
	            }
	            if(false == $model->allowField(true)->save($post,['id'=>$id])) {
	            	return $this->error('修改失败');
	            } else {
	            	return $this->success('修改管理员信息成功','admin/admin/index');
	            }
    		} else {
                
    			//非提交操作
    			$info['admin'] = $model->where(['id'=>$id])->find();
                $info['admin_cate'] = Db::name('admin_cate')->where(['type'=>1])->select();
    			$this->assign('info',$info);
    			return $this->fetch();
    		}
    	} else {
    		//是新增操作
    		if($this->request->isPost()) {
    			//是提交操作
    			$post = $this->request->post();
    			//验证  唯一规则： 表名，字段名，排除主键值，主键名
	            
				
				$rule = [
				    'name'  => 'require|alphaDash',
				    'password'  => 'require|confirm',
				    'password_confirm'  => 'require',
				    'admin_cate_id'   => 'require',
				];
				
				$msg = [
				    'name.require' 		=> '管理员名称不能为空',
				    'name.alphaDash'	=> '用户名格式只能是字母、数字、——或_',
				    'password.require'	=> '密码不能为空',
				    'password.confirm'	=> '两次密码不一致',
				    'password_confirm.require'	=> '重复密码不能为空',
				    'admin_cate_id.require'  => '请选择管理员分组',
				];
				$validate   = Validate::make($rule,$msg);
	            //验证部分数据合法性
	            if (!$validate->check($post)) {
	                $this->error('提交失败：' . $validate->getError());
	            }
	            //验证用户名是否存在
	            $name = $model->where(['name'=>$post['name'],'type'=>1])->find();
				
	            if(!empty($name)) {
	            	return $this->error('提交失败：该用户名已被注册');
	            }
	            //验证昵称是否存在
	            $nickname = $model->where(['nickname'=>$post['nickname'],'type'=>1])->find();
	            if(!empty($nickname)) {
	            	return $this->error('提交失败：该昵称已被占用');
	            }
	            //密码处理
	            $post['password'] = password($post['password']);
	            $post['type'] =1;
	            if(false == $model->allowField(true)->save($post)) {
	            	return $this->error('添加管理员失败');
	            } else {
	            	return $this->success('添加管理员成功','admin/admin/index');
	            }
    		} else {
    			//非提交操作
    			$info['admin_cate'] = Db::name('admin_cate')->where(['type'=>1])->select();
    			$this->assign('info',$info);
    			return $this->fetch();
    		}
    	}
    }

    /**
     * 修改密码
     * @return [type] [description]
     */
    public function editpassword()
    {
    	$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
		
    	if($id > 0) {
    		if($id == session('central_admin')) {
    			$post = $this->request->post();
    			
				$rule = [
				    'password'   => 'require|confirm',
				    'password_confirm' => 'require',
				];
				
				$msg = [
				    'password.require'  => '密码不能为空',
				    'password.confirm'  	=> '两次密码不一致',
				    'password_confirm.require'   => '重复密码不能为空',
				];
				$validate   = Validate::make($rule,$msg);
	            //验证部分数据合法性
	            if (!$validate->check($post)) {
	                $this->error('提交失败：' . $validate->getError());
	            }
    			$admin = Db::name('admin')->where(['id'=>$id,'type'=>1])->find();
    			if(password($post['password_old']) == $admin['password']) {
    				if(false == Db::name('admin')->where(['id'=>$id,'type'=>1])->update(['password'=>password($post['password'])])) {
    					return $this->error('修改失败');
    				} else {
    					return $this->success('修改成功');
    				}
    			} else {
    				return $this->error('原密码错误');
    			}
    		} else {
    			return $this->error('不能修改别人的密码');
    		}
    	} else {
            $id = session('central_admin');
            $this->assign('id',$id);
    		return $this->fetch();
    	}
    }


    /**
     * 管理员删除
     * @return [type] [description]
     */
    public function delete()
    {
    	if($this->request->isAjax()) {
    		$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    		if($id == 1) {
    			return $this->error('网站所有者不能被删除');
    		}
    		if($id == session('admin')) {
    			return $this->error('自己不能删除自己');
    		}
    		if(false == Db::name('admin')->where(['id'=>$id,'type'=>1])->delete()) {
    			return $this->error('删除失败');
    		} else {
    			return $this->success('删除成功','admin/admin/index');
    		}
    	}
    }


    /**
     * 管理员权限分组列表
     * @return [type] [description]
     */
    public function adminCate()
    {
    	return $this->fetch();

    }
	//管理员权限分组列表
	public function ajaxadminCate(){
	    if($this->request->isAjax()){
	        $model = new \app\admin\model\AdminCate;
			$get = input('get.');
			$where =[];
			if(!empty($get['keywords'])) {
			   $where['name'] = ['like', '%' . $get['keywords'] . '%'];
			}
	        if(!empty($get['time'])) {
	            $min_time = strtotime($get['time']);
	            $max_time = $min_time + 24 * 60 * 60;
	            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
	        }

	        $page       = ($get['page']-1)*$get['limit'];
	        $limit      = $get['limit'];
			$cate = $model->where($where)->where(['type'=>1])->limit($page,$limit)->order('create_time desc')->select();
	        $obj=array();
	        $obj['code']=0;
	        $obj['msg']="";
	        $obj['count']= $model->where($where)->where(['type'=>1])->limit($page,$limit)->order('create_time desc')->count();;
			$obj['data']=$cate;
	        return json($obj);
	    }else{
	        $this->error('非法请求');
	    }
	}
	/**
	 * 权限审核修改
	 * @access  public
	 * @param   int     id   字段id
	 * @param   string      返回标示
	 */
	public function checked(){
	    if($this->request->isPost()){
	        $post = $this->request->post();
	        $update_post['switch']     = $post['state'];
	        $update_post['update_time'] = time();
	        $res = Db::name('admin_cate')->where(['id'=>$post['id'],'city_id'=>$GLOBALS['city_id']])->update($update_post);
	        if($res) {return 1 ;} else {return 0;}
	    }
	}

    /**
     * 权限审核修改
     * @access  public
     * @param   int     id   字段id
     * @param   string      返回标示
     */
    public function checkeds(){
        if($this->request->isPost()){
            $post = $this->request->post();
            $update_post['is_switch']     = $post['state'];
            $update_post['update_time'] = time();
            $res = Db::name('admin_cate')->where(['id'=>$post['id'],'city_id'=>$GLOBALS['city_id']])->update($update_post);
            if($res) {return 1 ;} else {return 0;}
        }
    }

    /**
     * 管理员角色添加和修改操作
     * @return [type] [description]
     */
    public function adminCatePublish()
    {
        //获取角色id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new \app\admin\model\AdminCate();
        $menuModel = new AdminMenu();
        if($id > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '角色名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证用户名是否存在
                $name = $model->where(['name'=>$post['name'],'id'=>['neq',$post['id']],'type'=>1])->select();
                if(!empty($name)) {
                    return $this->error('提交失败：该角色名已存在');
                }
                //处理选中的权限菜单id，转为字符串
                if(!empty($post['ids'])) {
                    $post['permissions'] = implode(',',$post['ids']);
                } else {
                    $post['permissions'] = '0';
                }
                $post['update_time']=time();
                if(false == $model->allowField(true)->save($post,['id'=>$id,'type'=>1])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改角色信息成功','admin/admin/adminCate');
                }
            } else {
                //非提交操作
                $info['cate'] = Db::name('admin_cate')->where(['id'=>$id,'type'=>1])->find();
                if(!empty($info['cate']['permissions'])) {
                    //将菜单id字符串拆分成数组
                    $info['cate']['permissions'] = explode(',',$info['cate']['permissions']);
                }
                $menus = Db::name('admin_menu')->where('types',1)->select();
                $info['menu'] = $this->menulist($menus);
                $lists = $this->data_json($info['menu'],'ids[]',$info['cate']['permissions']);
                $this->assign('lists',json_encode($lists));
                $this->assign('info',$info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '角色名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证用户名是否存在
                $name = $model->where(['name'=>$post['name'],'type'=>1])->find();
                if(!empty($name)) {
                    return $this->error('提交失败：该角色名已存在');
                }
                
                //处理选中的权限菜单id，转为字符串
                if(!empty($post['ids'])) {
                    $post['permissions'] = implode(',',$post['ids']);
                    unset($post['ids']);
                }
                $post['type']=1;
                $post['create_time']=time();
                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加角色失败');
                } else {
                    return $this->success('添加角色成功','admin/admin/adminCate');
                }
            } else {
                //非提交操作
                $menus = Db::name('admin_menu')->where('types',1)->select();
                $info['menu'] = $this->menulist($menus);
                $lists = $this->data_json($info['menu'],'ids[]');
                // var_dump($lists);die;
                $this->assign('info',$info);
                $this->assign('lists',json_encode($lists));
                return $this->fetch();
            }
        }
    }
    
    /**
     * 数据转化
     * @return [data] [数据源]
     * @return [field] [节点字段名]
     * @return [old_datas] [默认选中数据]
     */
    public function data_json($data,$field,$old_datas=[]){
        foreach($data as $k=>$v){
            $list[$k]['title'] = $v['name'];
            $list[$k]['id'] = $v['id'];
            $list[$k]['field'] = $field;//节点字段名
            if(isset($v['list'])){
                $list[$k]['spread'] = true;//存在下级展开菜单
                $list[$k]['children'] = $this->data_json($v['list'],$field,$old_datas);
            }else{
                if(in_array($v['id'],$old_datas)){
                    $list[$k]['checked'] = true;//默认选中数据
                }
            }
        }
        return $list;
    }

    //权限预览
    public function preview()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new \app\admin\model\AdminCate();
        $info['cate'] = $model->where(['id'=>$id,'type'=>1])->find();
        if(!empty($info['cate']['permissions'])) {
            //将菜单id字符串拆分成数组
            $info['cate']['permissions'] = explode(',',$info['cate']['permissions']);
        }
        $menus = Db::name('admin_menu')->where('types',1)->select();
        $info['menu'] = $this->menulist($menus);
        $this->assign('info',$info);
        $lists = [];
        if(!empty($info['cate']['permissions'])){
            // 树状菜单
            $lists = $this->data_json($info['menu'],'ids[]',$info['cate']['permissions']);
        }
        
        
        $this->assign('lists',json_encode($lists));

        return $this->fetch();
    }


    protected function menulist($menu,$id=0,$level=0){

        static $menus = array();
        $size = count($menus)-1;
        foreach ($menu as $value) {
            if ($value['pid']==$id) {
                $value['level'] = $level+1;
                if($level == 0)
                {
                    $value['str'] = str_repeat('',$value['level']);
                    $menus[] = $value;
                }
                elseif($level == 2)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;'.'└ ';
                    $menus[$size]['list'][] = $value;
                }
                elseif($level == 3)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;'.'└ ';
                    $menus[$size]['list'][] = $value;
                }
                else
                {
                    $value['str'] = '&emsp;&emsp;'.'└ ';
                    $menus[$size]['list'][] = $value;
                }

                $this->menulist($menu,$value['id'],$value['level']);
            }
        }
        return $menus;
    }


    /**
     * 管理员角色删除
     * @return [type] [description]
     */
    public function adminCateDelete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if($id > 0) {
                if($id == 1) {
                    return $this->error('超级管理员角色不能删除');
                }
                if(Db::name('admin')->where(['admin_cate_id'=>$id,'type'=>1])->find() != null){
                    return $this->error('该角色下还有成员，不能删除');
                }
                if(false == Db::name('admin_cate')->where(['id'=>$id,'type'=>1])->delete()) {
                    return $this->error('删除失败');
                } else {
                    return $this->success('删除成功','admin/admin/adminCate');
                }
            } else {
                return $this->error('id不正确');
            }
        }
    }
}
